#pragma once

#include "wxtl/thread.h"
#include "wxtl/Socket.h"
#include "wxtl/CompletionPort.h"

class IocpServerSocket;
class BaseFiberClientHandler;



class BaseFiberServer: private wxtl::Thread
{
public:
	BaseFiberServer();
	void Listen(UINT port);
	void ShutDown();
	wxtl::Event& GetStopEvent();
	BaseFiberClientHandler* CreateClient();
	IocpServerSocket* CreateServerSocket();

	static void Initialize();

private:
	virtual void threadProc();
	void PostInitStatus( IocpServerSocket* client );
	void PostTimeoutStatus( IocpServerSocket* client );
	void WaitForFibers();
	virtual BaseFiberClientHandler* CreateFiberClientHandler() = 0;

protected:
	void SetMaxIocpThreads(size_t maxIocpThreads);
	void IncreaseFibersNumber();
	void DecreaseFibersNumber();

public:	
	
	UINT GetPort();

private:
	wxtl::Socket m_socket;
	wxtl::Event m_stop;
	wxtl::Event m_stopListen;
	wxtl::CompletionPort m_completionPort;
	size_t m_maxIocpThreads;
	volatile size_t m_numFibers;
};

